from typing import List, Optional
from pydantic import BaseModel, Field

from tools.sqllite.base_database_tool import BaseDatabaseTools


class HotelSearchParams(BaseModel):
    location: Optional[str] = Field(None, description="酒店位置，如城市名")
    price_tier: Optional[str] = Field(None, description="价格等级")
    min_rating: Optional[float] = Field(None, description="最低评分")

# 酒店管理工具集
class HotelManagementTools(BaseDatabaseTools):
    async def search_hotels(self, params: HotelSearchParams) -> List[dict]:
        """搜索酒店"""
        try:
            query = "SELECT * FROM hotels WHERE 1=1"
            conditions = []
            values = []

            if params.location:
                conditions.append("location LIKE ?")
                values.append(f"%{params.location}%")

            if params.price_tier:
                conditions.append("price_tier = ?")
                values.append(params.price_tier)

            if params.min_rating:
                conditions.append("rating >= ?")
                values.append(params.min_rating)

            if conditions:
                query += " AND " + " AND ".join(conditions)

            query += " ORDER BY rating DESC"
            print(f"Executing query: {query}")
            print(f"With values: {tuple(values)}")
            
            result = self._execute_query(query, tuple(values), fetch=True)
            print(f"Query result: {result}")
            return result if isinstance(result, list) else []
        except Exception as e:
            print(f"Error in search_hotels: {str(e)}")
            raise Exception(f"搜索酒店失败: {str(e)}")

    async def get_hotel_details(self, hotel_id: int) -> dict:
        """获取酒店详细信息"""
        try:
            result = self._execute_query(
                "SELECT * FROM hotels WHERE id = ?",
                (hotel_id,),
                fetch=True
            )
            return result[0] if result and isinstance(result, list) and len(result) > 0 else {}
        except Exception as e:
            raise Exception(f"获取酒店详情失败: {str(e)}")

    async def get_available_rooms(self, hotel_id: int) -> int:
        """获取可用房间数量"""
        try:
            result = self._execute_query(
                "SELECT available_rooms FROM hotels WHERE id = ?",
                (hotel_id,),
                fetch=True
            )
            return result[0]['available_rooms'] if result and isinstance(result, list) and len(result) > 0 else 0
        except Exception as e:
            raise Exception(f"获取可用房间失败: {str(e)}")